/**
 * 文档分类创建/编辑Modal组件
 */

import React, { useState, useEffect, useCallback } from 'react';
import { X } from 'lucide-react';
import type { DocumentCategory } from '@/types/document';
import { showMessage } from '@/components/common/MessageTip';

// 预设图标选项
const PRESET_ICONS = [
  '📁', '📊', '⚖️', '⚙️', '📖', '📄', '🏢', '💼', 
  '🔧', '📋', '📈', '🎯', '🔒', '⭐', '🏷️', '📌'
];

// 预设颜色选项
const PRESET_COLORS = [
  '#dc3545', '#28a745', '#007bff', '#6f42c1', 
  '#fd7e14', '#20c997', '#6c757d', '#e83e8c'
];

interface CategoryFormData {
  name: string;
  icon?: string;
  color?: string;
  description?: string;
  parent_id?: string | null;
}

interface CategoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (category: CategoryFormData) => Promise<void>;
  categoryToEdit?: DocumentCategory | null;
  isEditing: boolean;
  parentCategories: DocumentCategory[]; // 可选择的父分类列表
}

const CategoryModal: React.FC<CategoryModalProps> = ({
  isOpen,
  onClose,
  onSubmit,
  categoryToEdit,
  isEditing,
  parentCategories
}) => {
  const [formData, setFormData] = useState<CategoryFormData>({
    name: '',
    icon: '📁',
    color: '#007bff',
    description: '',
    parent_id: null
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 重置表单数据
  const resetForm = useCallback(() => {
    if (isEditing && categoryToEdit) {
      setFormData({
        name: categoryToEdit.name,
        icon: categoryToEdit.icon || '📁',
        color: categoryToEdit.color || '#007bff',
        description: categoryToEdit.description || '',
        parent_id: categoryToEdit.parent_id
      });
    } else {
      setFormData({
        name: '',
        icon: '📁',
        color: '#007bff',
        description: '',
        parent_id: null
      });
    }
    setErrors({});
  }, [isEditing, categoryToEdit]);

  // 当Modal打开或编辑数据变化时重置表单
  useEffect(() => {
    if (isOpen) {
      resetForm();
    }
  }, [isOpen, resetForm]);

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = '分类名称不能为空';
    } else if (formData.name.trim().length > 50) {
      newErrors.name = '分类名称不能超过50个字符';
    }

    if (formData.description && formData.description.length > 200) {
      newErrors.description = '描述不能超过200个字符';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);
    try {
      await onSubmit(formData);
      showMessage('success', isEditing ? '分类更新成功' : '分类创建成功');
      onClose();
    } catch (error) {
      showMessage('error', isEditing ? '分类更新失败' : '分类创建失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 处理输入变化
  const handleInputChange = (field: keyof CategoryFormData, value: string | null) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          {/* 标题栏 */}
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-xl font-semibold text-zinc-800">
              {isEditing ? '编辑分类' : '新建分类'}
            </h2>
            <button
              onClick={onClose}
              className="text-zinc-400 hover:text-zinc-600 transition-colors"
              type="button"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* 分类名称 */}
            <div>
              <label className="block text-sm font-medium text-zinc-700 mb-1">
                分类名称 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
                className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                  errors.name ? 'border-red-500' : 'border-zinc-300'
                }`}
                placeholder="请输入分类名称"
                maxLength={50}
              />
              {errors.name && (
                <p className="text-red-500 text-xs mt-1">{errors.name}</p>
              )}
            </div>

            {/* 图标选择 */}
            <div>
              <label className="block text-sm font-medium text-zinc-700 mb-2">
                分类图标
              </label>
              <div className="grid grid-cols-8 gap-2">
                {PRESET_ICONS.map((icon) => (
                  <button
                    key={icon}
                    type="button"
                    onClick={() => handleInputChange('icon', icon)}
                    className={`w-8 h-8 flex items-center justify-center rounded border-2 transition-colors ${
                      formData.icon === icon
                        ? 'border-blue-500 bg-blue-50'
                        : 'border-zinc-200 hover:border-zinc-300'
                    }`}
                  >
                    <span className="text-lg">{icon}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* 颜色选择 */}
            <div>
              <label className="block text-sm font-medium text-zinc-700 mb-2">
                分类颜色
              </label>
              <div className="flex flex-wrap gap-2">
                {PRESET_COLORS.map((color) => (
                  <button
                    key={color}
                    type="button"
                    onClick={() => handleInputChange('color', color)}
                    className={`w-8 h-8 rounded-full border-2 transition-all ${
                      formData.color === color
                        ? 'border-zinc-400 scale-110'
                        : 'border-zinc-200 hover:border-zinc-300'
                    }`}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>

            {/* 父分类选择 */}
            <div>
              <label className="block text-sm font-medium text-zinc-700 mb-1">
                父分类
              </label>
              <select
                value={formData.parent_id || ''}
                onChange={(e) => handleInputChange('parent_id', e.target.value || null)}
                className="w-full px-3 py-2 border border-zinc-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">无（根分类）</option>
                {parentCategories
                  .filter(cat => !isEditing || cat.id !== categoryToEdit?.id) // 编辑时排除自己
                  .map((category) => (
                    <option key={category.id} value={category.id}>
                      {category.icon} {category.name}
                    </option>
                  ))}
              </select>
            </div>

            {/* 描述 */}
            <div>
              <label className="block text-sm font-medium text-zinc-700 mb-1">
                描述
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => handleInputChange('description', e.target.value)}
                className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none ${
                  errors.description ? 'border-red-500' : 'border-zinc-300'
                }`}
                placeholder="请输入分类描述（可选）"
                rows={3}
                maxLength={200}
              />
              {errors.description && (
                <p className="text-red-500 text-xs mt-1">{errors.description}</p>
              )}
              <p className="text-zinc-400 text-xs mt-1">
                {formData.description?.length || 0}/200
              </p>
            </div>

            {/* 预览 */}
            <div className="bg-zinc-50 rounded-md p-3">
              <label className="block text-sm font-medium text-zinc-700 mb-2">
                预览效果
              </label>
              <div className="flex items-center space-x-2">
                <span className="text-lg">{formData.icon}</span>
                <span 
                  className="font-medium"
                  style={{ color: formData.color }}
                >
                  {formData.name || '分类名称'}
                </span>
              </div>
              {formData.description && (
                <p className="text-sm text-zinc-600 mt-1">{formData.description}</p>
              )}
            </div>

            {/* 按钮组 */}
            <div className="flex justify-end space-x-3 pt-4 border-t border-zinc-200">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 border border-zinc-300 text-zinc-700 rounded-md hover:bg-zinc-50 transition-colors"
                disabled={isSubmitting}
              >
                取消
              </button>
              <button
                type="submit"
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={isSubmitting}
              >
                {isSubmitting ? '保存中...' : (isEditing ? '更新' : '创建')}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default CategoryModal;
